package com.bitcat.firstapp.demo.musicdemo

import android.net.Uri
import android.os.Bundle
import android.widget.MediaController
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityVideoDemoBinding

class VideoDemoActivity : AppCompatActivity() {


    private val videoUrl = "http://192.168.1.4:8081/xiyouji.mp4"

    private val binding: ActivityVideoDemoBinding by lazy {
        ActivityVideoDemoBinding.inflate(layoutInflater)
    }

    private var exoPlayer:ExoPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //videoView
        val mediaController = MediaController(this)
        mediaController.setAnchorView(binding.videoView)


        binding.videoView.setMediaController(mediaController)
        binding.videoView.setVideoURI(Uri.parse(videoUrl))

        binding.btnVideoView.setOnClickListener {
            binding.videoView.start()
            binding.exoPlayerView.player?.pause()
        }


        //ExoPlayer
        exoPlayer = ExoPlayer.Builder(this).build().apply {
            //设置播放源
            setMediaItem(MediaItem.fromUri(videoUrl))
            //准备
            prepare()
        }
        binding.exoPlayerView.player = exoPlayer

        binding.btnExoPlayer.setOnClickListener {
            exoPlayer?.play() //播放
            binding.videoView.pause()
        }
    }


    override fun onPause() {
        super.onPause()
        binding.videoView.pause()
        exoPlayer?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        exoPlayer?.release() //释放资源
        exoPlayer = null //释放引用
    }
}